package com.sy.service.impl;

import com.alibaba.fastjson.JSON;
import com.sy.dto.ProvinceTreeNode;
import com.sy.entity.Province;
import com.sy.service.ProvinceService;
import com.sy.utils.RedisOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.sy.constant.BusinessConstant.*;

@Service
public class ProvinceServiceImpl extends BaseServiceImpl implements ProvinceService {
    @Autowired
    private RedisOperations redisOperations;
    @Override
    public List<ProvinceTreeNode> getAllProvinces() {
        List<ProvinceTreeNode> provinceTreeNodeList;
        if (redisOperations.exists(REDIS_PROVINCE_KEY)) {
            System.out.println("从Redis中直接获取...");
            provinceTreeNodeList = JSON.parseArray(redisOperations.get(REDIS_PROVINCE_KEY), ProvinceTreeNode.class);
        } else {
            System.out.println("从MySQL中查询...");
            provinceTreeNodeList = new ArrayList<>();
            //查询省
            List<Province> firstLevelProvinces = provinceMapper.getProvincesByProvinceId(ROOT_PROVINCE_PARENT_ID);
            for (Province firstLevelProvince : firstLevelProvinces) {
                ProvinceTreeNode provinceTreeNode = new ProvinceTreeNode();
                provinceTreeNode.setProvince(firstLevelProvince);
                //查询省对应的市区
                List<Province> secondLevelProvinces = provinceMapper.getProvincesByProvinceId(firstLevelProvince.getPid());
                List<ProvinceTreeNode> secondLevelNodeTrees = new ArrayList<>();
                for (Province secondLevelProvince : secondLevelProvinces) {
                    ProvinceTreeNode secondLevelProvinceTreeNode = new ProvinceTreeNode();
                    secondLevelProvinceTreeNode.setProvince(secondLevelProvince);
                    secondLevelNodeTrees.add(secondLevelProvinceTreeNode);
                }
                provinceTreeNode.setChildren(secondLevelNodeTrees);
                provinceTreeNodeList.add(provinceTreeNode);
            }
            //存入redis中
            redisOperations.set(REDIS_PROVINCE_KEY, JSON.toJSONString(provinceTreeNodeList));
        }
        return provinceTreeNodeList;
    }

    @Override
    public Province getProvinceByPid(Integer pid) {
        if (Objects.isNull(pid)) {
            pid = DEFAULT_CITY_ID;
        }
        return provinceMapper.getProvinceByPid(pid);
    }
}
